import React, { useContext } from "react";
import "./files.less";
import { PageContext } from "../pages/api/component/context";
import { Link } from "react-router-dom";
type fileProps = {
    children: React.ReactNode,
    onClick?: React.MouseEventHandler<HTMLElement>;
    data?: any;
    className?: string
}


function myhas(data:Array<any>, key: any) {
    for(let i = 0; i < data.length; i++) {
        if(data[i].key === key) {
            return i;
        }
    }
    return -1;
}

export function File(props: fileProps) {
    const pages = useContext(PageContext);
    const selectFileItem = (e: any) => {
        let pageArr = pages.pages.slice(0);
        if (myhas(pageArr,props.data.aid) === -1) {
            pageArr.push({
                name: props.data.name,
                key: props.data.aid
            });
        }
        pages.setPages(pageArr);
        pages.setNow({
            name: props.data.name,
            key: props.data.aid
        });
        sessionStorage.setItem("pages", JSON.stringify(pageArr));
        sessionStorage.setItem("now", JSON.stringify({
            name: props.data.name,
            key: props.data.aid
        }));
    }

    return (
        <Link to={"/index/project/apis/" + props.data.aid} style={{ color: "unset" }}>
            <div
                className={`file-item ${props.data.aid === pages.now.key ? " select" : ""} ${props.className}`}
                onClick={selectFileItem}
            >
                {props.children}
            </div>
        </Link>
    )
}